package bat.ke.qq.com;

import org.junit.Test;
import sun.reflect.generics.tree.Tree;

import java.util.*;

/**
 * lambda表达式解决了什么问题
 */
public class Testlambda {
    @Test
    /**
     * 匿名内部类
     */
    public void test1() {
        Comparator<Integer> comparator=new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        };
        TreeSet<Integer> ts=new TreeSet<>((x,y)->Integer.compare(x,y));
    }


    //需求：学员的年龄大于25的
    List<Student> studentList = Arrays.asList(
            new Student("a43", 18, 188, 35000),
            new Student("b53", 30, 188, 45000),
            new Student("c66", 26, 188, 55000),
            new Student("d110", 24, 188, 36000),
            new Student("e34", 32, 188, 43000)
    );

    public List<Student> filterStudent1(List<Student> list) {
        List<Student> result = new ArrayList<>();
        for (Student student : list) {
            if (student.getSalary() > 25000) {
                result.add(student);
            }
        }
        return result;
    }

    //需求2：身高超过170cm的
    public List<Student> filterStudent2(List<Student> list) {
        List<Student> result = new ArrayList<>();
        for (Student student : list) {
            if (student.getSize() > 170) {
                result.add(student);
            }
        }
        return result;
    }

    //优化方案1：策略模式 +  匿名内部类
    public List<Student> filterStudent3(List<Student> list, MyPredicate<Student> myPredicate) {
        List<Student> result = new ArrayList<>();
        for (Student student : list) {
            if (myPredicate.test(student)) {
                result.add(student);
            }
        }
        return result;
    }

    @Test
    public void test3() {
        List<Student> list = filterStudent3(studentList, new MyPredicate<Student>() {
            @Override
            public boolean test(Student o) {
                return o.getSalary() > 25000;
            }
        });

        for (Student student : list) {
            System.out.println(student);
        }
    }

    //优化方案2：lambda表达式
    @Test
    public void test4() {
        List<Student> students = filterStudent3(studentList, (x) -> x.getSalary() > 25000);
        students.forEach(System.out::println);
    }

    //优化方案3：stream api
    @Test
    public void test5() {
        studentList.stream()
                .filter((x) -> x.getSalary() > 25000)
                .filter((x) -> x.getAge() > 25)
                .limit(2)
                .forEach(System.out::println);
        System.out.println("---------------------");
        //提取所有的人名字
        studentList.stream()
                .map(Student::getName)
                .forEach(System.out::println);
    }


}
